package cn.demomaster.quickdb.sql;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.text.TextUtils;

import java.util.ArrayList;
import java.util.List;

import cn.demomaster.quickdb.TableHelper;
import cn.demomaster.quickdb.mapper.MapperManager;
import cn.demomaster.quickdb.model.ColumnInfo;
import cn.demomaster.quickdb.model.TableInfo;

public class SqlCreatorImpl extends SqlCreator {

    public SqlCreatorImpl(SQLiteOpenHelper sqLiteHelper) {
        super(sqLiteHelper);
    }

    @Override
    public <T> boolean insert(T model) {
        if(model==null){
            return false;
        }
        List models1 = new ArrayList<>();
        models1.add(model);
        return insertArray(models1, model.getClass());
    }

    public <T> boolean insertArray(List<T> models,Class<T> clazz) {
        if (models == null || models.isEmpty()) {
            return false;
        }
        SQLiteDatabase db = getDb();
        try {
            db.beginTransaction();
            String sql =  MapperManager.getInstance().getMapper(clazz).generateInsertSql(models,clazz);
            System.out.println("insertSql=" + sql);
            SQLiteStatement stat = db.compileStatement(sql);
            //db.execSQL(sql);
            long result = stat.executeInsert();
            db.setTransactionSuccessful();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != db) {
                    db.endTransaction();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    @Override
    public <T> boolean delete(T model) {
        return false;
    }

    @Override
    public boolean delete(String tableName, ContentValues contentValues) {
        try {
            if (contentValues != null && !contentValues.isEmpty()) {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("delete from ")
                        .append(tableName)
                        .append(" where ");
                boolean b = true;
                for (String key : contentValues.keySet()) {
                    stringBuilder.append((b ? " " : " and "))
                            .append(key)
                            .append("=")
                            .append(contentValues.get(key));
                    b = false;
                }
                System.out.println("sql=" + stringBuilder.toString());
                getDb().execSQL(stringBuilder.toString());
            } else {
                System.out.println("delete 条件语句限制请使用execDeleteSQL");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    @Override
    public <T> boolean deleteAll(String tableName) {
        String sql = "delete from " + tableName;//+" where 1=1";
        getDb().execSQL(sql);
        return true;
    }

    @Override
    public <T> boolean deleteAll(Class<T> clazz) {
        TableInfo tableInfo = TableHelper.getTableInfo(clazz);
        return deleteAll(tableInfo.getTableName());
    }

    @Override
    public <T> T modify(T model) {
        List<T> list = new ArrayList<>();
        list.add(model);
        String sql = MapperManager.getInstance().getMapper(model.getClass()).generateModifySql(list, model.getClass());
        System.out.println("sql=" + sql);
        try {
           getDb().execSQL(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean modifyArray(List models) {
        return false;
    }

    @Override
    public <T> T findOne(T model) {
        TableInfo tableInfo = TableHelper.getTableInfo(model.getClass());
        String[] params = new String[]{"*"};
        String whereParams = generateWhereParams(model);
        List<T> list = (List<T>) TableHelper.generateModels(tableInfo.getTableName(), params, whereParams, model.getClass(), false);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public <T> T findOne(String sql, Class<T> clazz) {
        List<T> list = TableHelper.generateModels2(sql, clazz, false);
        if (list == null || list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public <T> List<T> findArray(T model) {
        TableInfo tableInfo = TableHelper.getTableInfo(model.getClass());
        String[] params = new String[]{"*"};
        String whereParams = generateWhereParams(tableInfo);
        return (List<T>) TableHelper.generateModels(tableInfo.getTableName(), params, whereParams, model.getClass(), true);
    }

    @Override
    public <T> List<T> findArray(String sql, Class<T> clazz) {
        return TableHelper.generateModels2(sql, clazz, true);
    }

    public static <T> String generateWhereParams(T model) {
        if (model != null) {
            boolean isfirst = true;
            StringBuilder stringBuilder = new StringBuilder();
            List<ColumnInfo> columnList = MapperManager.getInstance().getMapper(model.getClass()).getColumnInfoList();
            for (ColumnInfo tableColumn : columnList) {
                    Object valueStr = MapperManager.getInstance().getMapper(model.getClass()).getFieldValue(model,tableColumn.getFieldName());
                    if (valueStr!=null) {
                        stringBuilder.append((isfirst ? "" : " and "))
                                .append(tableColumn.getColumnName())
                                .append("=")
                                .append(valueStr);
                        isfirst = false;
                    }
            }
            return stringBuilder.toString();
        }
        return null;
    }
}
